// import axios from  '@ohos/axios'
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from '@ohos/axios';
import { promptAction } from '@kit.ArkUI';
import signatureString from '../utils/sign-helper';

const sign_helper = new signatureString();

class BaseRequest {
  instance: AxiosInstance;

  constructor(config: AxiosRequestConfig<AxiosResponse>) {
    this.instance = axios.create(config);

    // 请求拦截
    this.instance.interceptors.request.use((config) => {
      const token = '861fbf3585c45899bb99380e131a6e77387a9443';
      // if (token) {
      //   config.headers.token = token;
      //   config.headers.uuid = "65f795380899d0064b642e63";
      //   config.headers.openid = "onHt962ioX89J_F5KMgGGzWFjimA";
      // }
      config.headers.Authorization = "Bearer " + token;
      config.headers.uuid = "65f66ccdf07310a97cd224305";
      config.headers.openid = "onHt96-rTWgFFmR4HzeVDiaQz8NE";
      config.params.platform = "wx"
      config.params.channel = "mini"
      config.params.version = "1.0.0"
      config.params.app_id = 10000
      config.params.timestamp = Math.floor(new Date().getTime() / 1000)
      config.params.sign = sign_helper.getSign(
        config.params,
        "123456ABCDEFGHIJKL{(&#!,.&*)}MNOLQRSTUVWXYZ789010000"
      );
      console.log('Request config', JSON.stringify(config));
      return config;
    }, (err) => {
      console.error('Request error', err);
      return Promise.reject(err);
    }
    );

    // 响应拦截
    this.instance.interceptors.response.use((response: AxiosResponse<any, any>) => {
      let data = response.data;
      console.log('Response data', JSON.stringify(data));
      if (typeof data === 'string') {
        data = JSON.parse(data.trim());
      }
      const { status, msg, result } = data;
      if (status === 1) { // 处理成功情况
        return result;
      } else if (status === 400) { // 处理错误码
        promptAction.showToast({
          message: msg
        });
        return Promise.reject(new Error(msg));
      } else if (status === 500) {
        promptAction.showToast({
          message: msg
        });
        return response.data;
      } else { // 处理其他错误码
        promptAction.showToast({
          message: msg
        });
        return Promise.reject(new Error(msg));
      }
    }, (err) => {
      console.error('Response error', err);
      return Promise.reject(err);
    }
    );
  }

  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    console.log('Request config', config);
    return this.instance.request<any, T>(config);
  }

  get<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' });
  }

  post<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' });
  }
}

export const axiosAPI = new BaseRequest({
  baseURL: 'http://www.xsmsdj.cn',
  timeout: 60000
})
